package com.demo.demo.itext7.page;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import java.io.IOException;

/**
 * Created by kdl on 2018/9/3.
 */
public class PageEventHandler implements IEventHandler {
    public void handleEvent(Event event) {
        PdfFont font2 = null;
        try {
            font2 = PdfFontFactory.createFont("D:\\MYingHei.ttf", PdfEncodings.IDENTITY_H, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        int pageNumber = pdf.getPageNumber(page);
        if(pageNumber==1){
            return;
        }
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(
                page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
        canvas.setFontSize(8F);
        float x = (float) ((pageSize.getLeft() + pageSize.getRight()) /1.32);
        float y = pageSize.getBottom() + 750;
        try {
            Paragraph p = new Paragraph();
            p.setFont(font2);
            p.add("Date 日期: 2022-02-02\n");
            p.add("Page No ⾴數: " + pageNumber);
            canvas.showTextAligned(p, x, y, TextAlignment.LEFT);
            canvas.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
